import React, { useEffect, useState } from 'react'
import {
    selectClassAsync,
    updateClassAsync,
    deleteClassAsync,
    createClassAsync
} from '../../api/class'
import { selectStudentAsync } from '../../api/student'
import { Table, Space, Button, Popconfirm } from 'antd'
import './style.less'
import EditForm from './EditForm'

function ClassPage() {
    // class原始数据
    const [classData, setClassData] = useState([])
    // student原始数据
    const [studentData, setStudentData] = useState([])
    // 真正渲染在表格中的数据
    const [showData, setShowData] = useState([])
    // 对话框对应的是修改数据（true）还是添加数据（false）
    const [isEdit, setIsEdit] = useState(false)
    // 添加/修改数据对话框是否显示
    const [modalVisible, setModalVisible] = useState(false)
    // 待传入添加/修改对话框中的数据
    const [modalData, setModalData] = useState([])
    // 表格是否在渲染等待
    const [tableLoading, setTableLoading] = useState(false)

    // 异步请求函数抽象提取
    const asyncRequest = async (fn, payload) => {
        payload = payload || []
        const res = await fn(...payload)
        if (res.code === 0) {
            return res.data ? res.data : true
        }
    }

    useEffect(() => {
        setTableLoading(true)
        async function asyncFn() {
            setClassData(await asyncRequest(selectClassAsync))
            setStudentData(await asyncRequest(selectStudentAsync))
            setTableLoading(false)
        }
        asyncFn()
    }, [])
    useEffect(() => {
        setShowData(
            classData.map((item, i) => {
                item.index = i + 1
                item.studentNum = studentData.reduce((num, cell) => {
                    if (+cell.classNo === +item.no) {
                        num = num + 1
                    }
                    return num
                }, 0)
                return item
            })
        )
    }, [classData, studentData])

    // 手动添加按钮点击事件
    const addButtonEvent = () => {
        setIsEdit(false)
        setModalData({ type: 'C', no: null, name: '' })
        setModalVisible(true)
    }
    // 修改按钮点击事件
    const editButtonEvent = (text, record) => {
        // console.log(text, record)
        setIsEdit(true)
        setModalData(record)
        setModalVisible(true)
    }
    // 删除按钮点击事件
    const deleteButtonEvent = async (text, record) => {
        setTableLoading(true)
        if (await asyncRequest(deleteClassAsync, [record.no])) {
            setClassData(await asyncRequest(selectClassAsync))
            setTableLoading(false)
        }
    }
    // 添加/修改对话框中按钮点击事件
    // 对话框中确定按钮点击事件
    const modalOk = async (data, oldData) => {
        setModalVisible(false)
        setTableLoading(true)
        if (isEdit) {
            if (await asyncRequest(updateClassAsync, [data, oldData])) {
                setClassData(await asyncRequest(selectClassAsync))
                setTableLoading(false)
            }
        } else {
            if (await asyncRequest(createClassAsync, [data])) {
                setClassData(await asyncRequest(selectClassAsync))
                setTableLoading(false)
            }
        }
    }
    // 对话框中取消按钮点击事件
    const modalCancel = () => {
        setModalVisible(false)
    }
    // 表单输入时，检查编号是否重复
    const isRepeat = (no) => {
        return showData.some((item) => +item.no === +no)
    }

    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            sorter: (a, b) => a.index - b.index
        },
        {
            title: '班级编号',
            dataIndex: 'no',
            key: 'no',
            sorter: (a, b) => a.no - b.no
        },
        {
            title: '班级名称',
            dataIndex: 'name',
            key: 'name'
        },
        {
            title: '学生人数',
            dataIndex: 'studentNum',
            key: 'studentNum',
            sorter: (a, b) => a.studentNum - b.studentNum
        },
        {
            title: '操作',
            dataIndex: 'handle',
            key: 'handle',
            render: (text, record) => (
                <Space size="middle">
                    <Button
                        type="primary"
                        onClick={() => {
                            editButtonEvent(text, record)
                        }}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="是否确认删除？"
                        onConfirm={() => {
                            deleteButtonEvent(text, record)
                        }}
                        okText="删除"
                        cancelText="取消"
                    >
                        <Button type="danger">删除</Button>
                    </Popconfirm>
                </Space>
            )
        }
    ]

    return (
        <div className="class-page-container">
            <div className="button-header">
                <Button type="primary" onClick={addButtonEvent}>
                    添加班级
                </Button>
            </div>
            <Table
                dataSource={showData}
                columns={columns}
                rowKey={(item) => item.no}
                loading={tableLoading}
            />
            <EditForm
                modalVisible={modalVisible}
                modalOk={modalOk}
                modalCancel={modalCancel}
                isEdit={isEdit}
                modalData={modalData}
                isRepeat={isRepeat}
            />
        </div>
    )
}

export default ClassPage
